package br.gendi.dialog;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.PlatformUI;

import br.gendi.beans.BaseGenomica;
import br.gendi.beans.Parametros;
import br.gendi.core.Util;
import br.gendi.rcp.NavigationView;

public class ConfiguracoesBases {

	private Shell sShell = null;  //  @jve:decl-index=0:visual-constraint="10,10"
	private TabFolder tabFolder = null;
	private Composite composite = null;
	private Composite composite1 = null;
	private Composite composite2 = null;
	private Composite composite3 = null;
	private ScrolledComposite scComposite = null;
	private Label label = null;
	private Text text = null;
	private Button btnSalvar = null;
	private Button btnRemover = null;
	private Label label2 = null;
	private Text text1 = null;
	private Label label1 = null;
	private Button checkBox = null;
	private BaseGenomica base = null;


	public ConfiguracoesBases() {
		super();
		createSShell();
	}

	public ConfiguracoesBases(BaseGenomica b) {
		super();
		createSShell();
		text.setText(b.getTitulo());
		text1.setText(b.getUrl());
		//text2.setText(b.getFormAction());

		criarCamposVirtuais(b, composite2);
		base = b;
	}

	private void createSShell() {
		GridLayout gridLayout = new GridLayout();
		gridLayout.horizontalSpacing = 2;
		gridLayout.marginWidth = 2;
		gridLayout.marginHeight = 2;
		gridLayout.verticalSpacing = 2;
		sShell = new Shell();
		sShell.setText("Configurações");

		ImageData isLarge = br.gendi.rcp.Activator.getImageDescriptor("/icons/mainicon32.png").getImageData();
		ImageData isSmall = br.gendi.rcp.Activator.getImageDescriptor("/icons/mainicon16.png").getImageData();

		Image large = new Image(sShell.getDisplay(), isLarge);
		Image small = new Image(sShell.getDisplay(), isSmall);

		sShell.setImages(new Image[] {small, large});
		createTabFolder();
		sShell.setLayout(gridLayout);
		//createComposite3();
		//sShell.setSize(600, 400);
		sShell.setMinimumSize(600,400);
		Rectangle pDisplayBounds = sShell.getDisplay().getBounds();
		
        // Set Width and Height(doesn't matter value)
		int nMinWidth = pDisplayBounds.width  / 2;
		int nMinHeight = pDisplayBounds.height / 2;

         // This formulae calculate the shell's Left ant Top
		int nLeft = (pDisplayBounds.width - nMinWidth) / 2;
		int nTop = (pDisplayBounds.height - nMinHeight) / 2;
              
          // Set shell bounds,
		sShell.setBounds(nLeft, nTop, nMinWidth, nMinHeight);

		sShell.open();
		
		this.actions();
	}

	@SuppressWarnings("deprecation")
	private void salvarConfiguracao() throws IOException, ClassNotFoundException {
		base.setTitulo(validarTitulo(text.getText()));
		File f2 = new File(Util.SAVE_PATH);
		if (!f2.exists())
			f2.mkdirs();
		File f = new File(Util.SAVE_PATH + base.getTitulo());
		if (!f.exists())
			f.createNewFile();
		else {
			boolean confirm = MessageDialog.openConfirm(sShell, "configuração existente", "Base com titulo já existente.\n\nClique em 'OK' para sobrescrever.\n'Cancelar' para cancelar o processo.");
			if (confirm != true)
				return;
		}

		ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(f)); 
		out.writeObject(base);
		out.flush();
		out.close(); 

		IViewPart[] views = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getViews();
		NavigationView nv = null;
		for (int i=0; i<views.length; i++)
			if (views[i] instanceof NavigationView) {
				nv = (NavigationView) views[i];
				break;
			}

		nv.carregarItens();
		sShell.close();
	}


	public String validarTitulo(String titulo){												//Metodo feito para adequa��o do T�tulo da base g�nomica.
		char[] cs = {'\"','!','@',',','#','$','%','�','&','*','(',')','+'
				,'_','\'','�','�','�','�','�','�','�','�','`','�','�','�',':'}; //Caracteres que ser�o alterados
		//boolean check = false; 																//Variavel de controle
		for(int indiceTitulo = 0;indiceTitulo<titulo.length();indiceTitulo++){				//La�o do t�tulo
			for(int indiceCS = 0;indiceCS<cs.length;indiceCS++){							//La�o dos caracteres
				if(titulo.charAt(indiceTitulo) == cs[indiceCS]){							//Verificando se o caractere do titulo existe no vetor de caracteres 
					//check = true;															//Se sim, � assinalado que existe um caractere a ser trocado.
					titulo = titulo.replace(titulo.charAt(indiceTitulo), ' '); 				// atualizando o titulo trocando o caractere "proibido"
				}								
			}

		}
		return titulo;																		//Retornando o titulo depois de verificado.		
	}


	private void removerConfiguracao() throws FileNotFoundException, IOException, ClassNotFoundException {
		boolean remover = MessageDialog.openQuestion(sShell, "EPIDI", "Tem certeza que gostaria de remover esta configuração ?");
		if (remover == false)
			return;


		File f = new File(Util.SAVE_PATH + base.getTitulo());
		if (f.exists()) {
			f.delete();
		}						
		else
			return;

		IViewPart[] views = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getViews();
		NavigationView nv = null;
		for (int i=0; i<views.length; i++)
			if (views[i] instanceof NavigationView) {
				nv = (NavigationView) views[i];
				break;
			}
		nv.removerItens();
		nv.carregarItens();
		MessageDialog.openInformation(sShell, "Remover", "Configuração removida com sucesso.");
		try {
			nv.carregarItens();
		} catch (Exception e) {
			e.printStackTrace();
		}
		sShell.close();
	}

	//botao salvar
	private void actions() {
		btnSalvar.addSelectionListener(new SelectionListener() {
			public void widgetDefaultSelected(SelectionEvent arg0) {

			}
			public void widgetSelected(SelectionEvent arg0) {

				try {
					salvarConfiguracao();
				} catch (IOException e) {
					MessageDialog.openError(sShell, "EPIDI: Erro", e.toString());
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					MessageDialog.openError(sShell, "EPIDI: Erro", e.toString());
					e.printStackTrace();
				}
			}
		});

		//botao remover
		btnRemover.addSelectionListener(new SelectionListener() {
			public void widgetDefaultSelected(SelectionEvent arg0) {

			}
			public void widgetSelected(SelectionEvent arg0) {
				try {
					removerConfiguracao();
				} catch (FileNotFoundException e) {
					MessageDialog.openError(sShell, "EPIDI: Erro", e.toString());
					e.printStackTrace();
				} catch (IOException e) {	
					MessageDialog.openError(sShell, "EPIDI: Erro", e.toString());
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					MessageDialog.openError(sShell, "EPIDI: Erro", e.toString());
					e.printStackTrace();
				}

			}
		});

	}

	private void createTabFolder() {
		GridData gridData = new GridData();
		gridData.horizontalAlignment = GridData.FILL;
		gridData.grabExcessHorizontalSpace = true;
		gridData.grabExcessVerticalSpace = true;
		gridData.verticalAlignment = GridData.FILL;
		tabFolder = new TabFolder(sShell, SWT.NONE);
		tabFolder.setLayoutData(gridData);
		createComposite();
		createComposite2();
		TabItem tabItem = new TabItem(tabFolder, SWT.NONE);
		tabItem.setText("Informações gerais");
		tabItem.setControl(composite);
		composite.setSize(700, 400);
		TabItem tabItem1 = new TabItem(tabFolder, SWT.NONE);
		tabItem1.setText("Parâmetros");
		tabItem1.setControl(composite2);
	}

	private void createComposite() {
		GridData gridData8 = new GridData();
		gridData8.grabExcessHorizontalSpace = true;
		gridData8.verticalAlignment = GridData.CENTER;
		gridData8.horizontalSpan = 3;
		gridData8.horizontalAlignment = GridData.FILL;
		GridData gridData7 = new GridData();
		gridData7.grabExcessHorizontalSpace = true;
		gridData7.verticalAlignment = GridData.CENTER;
		gridData7.horizontalSpan = 3;
		gridData7.horizontalAlignment = GridData.FILL;
		GridData gridData6 = new GridData();
		gridData6.horizontalAlignment = GridData.BEGINNING;
		gridData6.verticalAlignment = GridData.CENTER;
		GridData gridData5 = new GridData();
		gridData5.horizontalAlignment = GridData.FILL;
		gridData5.grabExcessHorizontalSpace = true;
		gridData5.horizontalSpan = 3;
		gridData5.verticalAlignment = GridData.CENTER;
		GridData gridData4 = new GridData();
		gridData4.horizontalAlignment = GridData.FILL;
		gridData4.grabExcessHorizontalSpace = true;
		gridData4.horizontalSpan = 3;
		gridData4.verticalAlignment = GridData.CENTER;
		GridData gridData3 = new GridData();
		gridData3.horizontalAlignment = GridData.BEGINNING;
		gridData3.verticalAlignment = GridData.CENTER;
		GridData gridData2 = new GridData();
		gridData2.horizontalAlignment = GridData.BEGINNING;
		gridData2.verticalAlignment = GridData.CENTER;
		GridLayout gridLayout1 = new GridLayout();
		gridLayout1.numColumns = 4;
		composite = new Composite(tabFolder, SWT.NONE);
		composite.setLayout(gridLayout1);
		label = new Label(composite, SWT.NONE);
		label.setText("Nome:");
		label.setLayoutData(gridData3);
		text = new Text(composite, SWT.BORDER);
		text.setLayoutData(gridData5);
		label2 = new Label(composite, SWT.NONE);
		label2.setText("URL:");
		label2.setLayoutData(gridData2);
		text1 = new Text(composite, SWT.BORDER);
		text1.setLayoutData(gridData4);
		label1 = new Label(composite, SWT.NONE);
		label1.setText("Habilitado:");
		label1.setLayoutData(gridData6);
		checkBox = new Button(composite, SWT.CHECK);
		checkBox.setLayoutData(gridData7);

		createComposite3();
		createComposite1();
	}

	private void createComposite2() {
		GridLayout gridLayout4 = new GridLayout();
		gridLayout4.numColumns = 4;
		composite2 = new Composite(tabFolder, SWT.NONE);
		//composite2.setSize(new Point(572, 334));
		composite2.setLayout(gridLayout4);
	}

	private void createComposite1() {
		GridData gridData1 = new GridData();
		gridData1.grabExcessHorizontalSpace = true;
		gridData1.horizontalAlignment = GridData.END;
		gridData1.verticalAlignment = GridData.END;
		gridData1.grabExcessVerticalSpace = true;
		GridLayout gridLayout2 = new GridLayout();
		gridLayout2.numColumns = 2;
		gridLayout2.verticalSpacing = 3;
		gridLayout2.marginWidth = 3;
		gridLayout2.marginHeight = 3;
		gridLayout2.horizontalSpacing = 3;
		composite1 = new Composite(composite3, SWT.NONE);
		composite1.setLayout(gridLayout2);
		composite1.setLayoutData(gridData1);
		btnSalvar = new Button(composite1, SWT.NONE);
		btnSalvar.setText("&Salvar");
		btnRemover = new Button(composite1, SWT.NONE);
		btnRemover.setText("&Remover");
	}


	private ArrayList<Button> posicaoSelecionado = null;

	/**
	 * @param b
	 * @param composite3
	 */
	private void criarCamposVirtuais(final BaseGenomica b, Composite composite3) {

		if (b.isAtivo())
			checkBox.setSelection(true);
		else
			checkBox.setSelection(false);

		posicaoSelecionado = null;
		posicaoSelecionado = new ArrayList<Button>();

		checkBox.addSelectionListener(new SelectionListener() {
			public void widgetDefaultSelected(SelectionEvent arg0) {

			}
			public void widgetSelected(SelectionEvent arg0) {
				b.setAtivo(((Button)arg0.widget).getSelection());
			}
		});

		ArrayList<Parametros> a1 = b.getParametros();

		Label label3;
		GridData gridData = new GridData();
		gridData.horizontalAlignment = GridData.FILL_HORIZONTAL;
		gridData.grabExcessHorizontalSpace = true;
		gridData.verticalAlignment = GridData.CENTER;

		final ArrayList<Text> descricoes = new ArrayList<Text>();

		label3 = new Label(composite3, SWT.NONE);

		label3 = new Label(composite3, SWT.NONE);
		label3.setText("Nome");
		label3.setFont(new Font(sShell.getDisplay(), new FontData("Tahoma", 8, SWT.BOLD)));

		label3 = new Label(composite3, SWT.NONE);
		label3.setText("Valor");
		label3.setFont(new Font(sShell.getDisplay(), new FontData("Tahoma", 8, SWT.BOLD)));

		label3 = new Label(composite3, SWT.NONE);
		label3.setText("Comentário");
		label3.setFont(new Font(sShell.getDisplay(), new FontData("Tahoma", 8, SWT.BOLD)));



		for (int i=0; i < a1.size(); i++) {
			final Parametros p = a1.get(i);

			Button bAtivo = new Button(composite3, SWT.RADIO);
			posicaoSelecionado.add(bAtivo);

			if (p.isBusca()==true) {
				bAtivo.setSelection(true);
			}

			bAtivo.addSelectionListener(new SelectionListener() {
				public void widgetDefaultSelected(SelectionEvent arg0) {

				}
				public void widgetSelected(SelectionEvent arg0) {
					Button bt = (Button) arg0.getSource();

					if (bt.getSelection()==false) {
						p.setBusca(false);
					} else {
						p.setBusca(true);
						return;
					}
				}
			});

			label3 = new Label(composite3, SWT.NONE);
			label3.setText(p.getNome());
			label3.setToolTipText(p.getTipoCampo());

			if (p.getTipoCampo().equals("text") || p.getTipoCampo().equals("textarea")) { //textarea

				final Text text2 = new Text(composite3, SWT.BORDER);

				if (p.getValorAtual() != null)
					text2.setText(p.getValorAtual());
				else
					if (p.getValorPadrao() != null)
						text2.setText(p.getValorPadrao());

				text2.addModifyListener(new ModifyListener() {
					public void modifyText(ModifyEvent arg0) {
						p.setValorAtual(text2.getText());
					}
				});

			} //textarea fim
			else 
				if (p.getTipoCampo().startsWith("select")) { //select
					Combo c;
					if (p.getTipoCampo().equals("select_single")) {
						c = new Combo(composite3, SWT.BORDER | SWT.READ_ONLY | SWT.V_SCROLL);
					}else {
						c = new Combo(composite3, SWT.BORDER | SWT.READ_ONLY | SWT.V_SCROLL | SWT.MULTI);
					}

					Collection _valores = p.getValores();
					for (Iterator _v = _valores.iterator(); _v.hasNext();)
						c.add((String) _v.next());

					if (c.getItemCount() > 0)
						c.select(0);

					c.addSelectionListener(new SelectionListener() {
						public void widgetDefaultSelected(SelectionEvent arg0) {

						}
						public void widgetSelected(SelectionEvent arg0) {
							Combo comb = (Combo) arg0.widget;
							p.setValorAtual(comb.getItem(comb.getSelectionIndex()));
						}
					});

					if (p.getValorAtual() != null)
						if (p.getValorAtual().length() > 0) {
							for (int i2=0; i2<c.getItemCount(); i2++) {
								if (c.getItem(i2).equalsIgnoreCase(p.getValorAtual())) {
									c.select(i2);
									break;
								}
							}
						}
				}	//select fim
				else 	
					if (p.getTipoCampo().startsWith("checkbox") || p.getTipoCampo().startsWith("radio"))  { //checkbox

						if (p.getTipoCampo().startsWith("checkbox")) {
							
							Combo c;
							c = new Combo(composite3, SWT.BORDER | SWT.READ_ONLY | SWT.V_SCROLL);

							Collection _valores = p.getValores();
							for (Iterator _v = _valores.iterator(); _v.hasNext();)
								c.add((String) _v.next());

							if (c.getItemCount() > 0)
								c.select(0);

							c.addSelectionListener(new SelectionListener() {
								public void widgetDefaultSelected(SelectionEvent arg0) {

								}
								public void widgetSelected(SelectionEvent arg0) {
									Combo comb = (Combo) arg0.widget;
									p.setValorAtual(comb.getItem(comb.getSelectionIndex()));
								}
							});

							if (p.getValorAtual() != null)
								if (p.getValorAtual().length() > 0) {
									for (int i2=0; i2<c.getItemCount(); i2++) {
										if (c.getItem(i2).equalsIgnoreCase(p.getValorAtual())) {
											c.select(i2);
											break;
										}
									}
								}

						} else {

							Button b3 = new Button(composite3, SWT.CHECK);
							b3.addSelectionListener(new SelectionListener() {
								public void widgetDefaultSelected(SelectionEvent arg0) {

								}
								public void widgetSelected(SelectionEvent arg0) {
									Button button = (Button) arg0.widget;
									if (button.getSelection() == true) {
										p.setValorAtual("true");
									} else {
										p.setValorAtual("false");
									}
								}
							});
							if (p.getValorAtual() != null) {
								if (p.getValorAtual().equalsIgnoreCase("true"))
									b3.setSelection(true);
								else
									b3.setSelection(false);
							}
						}

					} //checkbox fim 
					else 
						if (p.getTipoCampo().equals("hidden")) { //hidden
							//campos hidden não devem ser visualizados.

							final Text text2 = new Text(composite3, SWT.BORDER);

							if (p.getValorAtual() != null)
								text2.setText(p.getValorAtual());
							else
								if (p.getValorPadrao() != null)
									text2.setText(p.getValorPadrao());

							text2.setEnabled(false);


						} //hidden fim
						else if (p.getTipoCampo().equals("file")) { //file
							final Text text2 = new Text(composite3, SWT.BORDER);

							if (p.getValorAtual() != null)
								text2.setText(p.getValorAtual());
							else
								if (p.getValorPadrao() != null)
									text2.setText(p.getValorPadrao());

							text2.addModifyListener(new ModifyListener() {
								public void modifyText(ModifyEvent arg0) {
									p.setValorAtual(text2.getText());
								}
							});

						} //file end
						else if (p.getTipoCampo().startsWith("submit"))  { //submit
							Button b3 = new Button(composite3, SWT.CHECK);
							b3.addSelectionListener(new SelectionListener() {
								public void widgetDefaultSelected(SelectionEvent arg0) {

								}
								public void widgetSelected(SelectionEvent arg0) {
									Button button = (Button) arg0.widget;
									if (button.getSelection() == true) {
										p.setValorAtual("true");
									} else {
										p.setValorAtual("false");
									}
								}
							});
							if (p.getValorAtual() != null) {
								if (p.getValorAtual().equalsIgnoreCase("true"))
									b3.setSelection(true);
								else
									b3.setSelection(false);
							}

						} //submit fim 
						else {
							System.out.println(p.getTipoCampo() + " ?? ");
							new Button(composite3, SWT.CHECK);
						}

			GridData gridData6 = new GridData();
			gridData6.horizontalAlignment = GridData.FILL;
			gridData6.grabExcessHorizontalSpace = true;
			gridData6.verticalAlignment = GridData.CENTER;
			Text text3 = new Text(composite3, SWT.BORDER);
			text3.setLayoutData(gridData6);
			text3.addModifyListener(new ModifyListener() {
				public void modifyText(ModifyEvent arg0) {
					Text t = (Text) arg0.widget;
					p.setDescricao(t.getText());
				}
			});

			try {
				text3.setText(p.getDescricao());
			} catch (Exception e) {
				continue;
			}

			descricoes.add(text3);
		} //fim do for
		composite3.redraw();
		composite3.update();
		composite3.pack();		
	}

	private void createComposite3() {
		GridData gridData9 = new GridData();
		gridData9.horizontalAlignment = GridData.FILL;
		gridData9.grabExcessHorizontalSpace = true;
		gridData9.verticalAlignment = GridData.CENTER;
		GridLayout gridLayout3 = new GridLayout();
		gridLayout3.horizontalSpacing = 1;
		gridLayout3.marginWidth = 1;
		gridLayout3.marginHeight = 1;
		gridLayout3.verticalSpacing = 1;
		composite3 = new Composite(sShell, SWT.NONE);
		composite3.setLayout(gridLayout3);
		composite3.setLayoutData(gridData9);
	}
}
